<template>
    <div class="announcement-container">
        <!-- 搜索区域 -->
        <el-card class="search-card">
            <el-form :inline="true" :model="searchForm" class="search-form">
                <el-form-item label="标题">
                    <el-input v-model="searchForm.searchQuery" placeholder="请输入搜索内容" clearable />
                </el-form-item>
                <el-form-item label="状态" style="width: 160px;">
                    <el-select v-model="searchForm.isVisible" placeholder="请选择状态" clearable>
                        <el-option label="展示" :value="1" />
                        <el-option label="不展示" :value="0" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">
                        <el-icon>
                            <Search />
                        </el-icon>搜索
                    </el-button>
                    <el-button @click="resetSearch">
                        <el-icon>
                            <Refresh />
                        </el-icon>重置
                    </el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <!-- 表格区域 -->
        <el-card class="table-card">
            <template #header>
                <div class="card-header">
                    <span>公告列表</span>
                    <el-button type="primary" @click="handleAdd">
                        <el-icon>
                            <Plus />
                        </el-icon>新增公告
                    </el-button>
                </div>
            </template>

            <el-table v-loading="loading" :data="tableData" border style="width: 100%">
                <el-table-column prop="announcementId" label="ID" width="80" />
                <el-table-column prop="anTitle" label="标题" min-width="80" show-overflow-tooltip />
                <el-table-column prop="anContent" label="内容" min-width="180" show-overflow-tooltip />
                <el-table-column prop="adminId" label="发布人" width="120" />
                <el-table-column prop="publishTime" label="发布时间" width="180" />
                <el-table-column prop="is_visible" label="状态" width="100">
                    <template #default="scope">
                        <el-tag :type="scope.row.isVisible ? 'success' : 'info'">
                            {{ scope.row.isVisible ? '展示' : '不展示' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="250" fixed="right">
                    <template #default="scope">
                        <el-button-group>
                            <el-button type="primary" :icon="Edit" link @click="handleEdit(scope.row)">
                                编辑
                            </el-button>
                            <el-button type="danger" :icon="Delete" link @click="handleDelete(scope.row)">
                                删除
                            </el-button>
                        </el-button-group>
                        <el-switch v-model="scope.row.isVisible" :active-value="1" :inactive-value="0"
                            @change="handleSwitchChange(scope.row)" style="margin-left: 8px" />
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination-container">
                <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
                    :page-sizes="[10, 20, 50, 100]" :total="pagination.total"
                    layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange" />
            </div>
        </el-card>
    </div>
    <Dialog :title="dialog.title" :width="dialog.width" :height="dialog.height" :visible="dialog.visible"
        @on-close="onClose" @on-confirm="commit">
        <el-form :model="form" ref="formRef" label-width="100px" :rules="rule">
            <el-form-item label="公告标题" prop="anTitle">
                <el-input v-model="form.anTitle" placeholder="请输入公告标题"></el-input>
            </el-form-item>
            <el-form-item label="公告内容" prop="anContent">
                <el-input type="textarea" v-model="form.anContent" placeholder="请输入公告内容"></el-input>
            </el-form-item>
        </el-form>

    </Dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'
import { Search, Plus, Edit, View, Delete, Refresh } from '@element-plus/icons-vue'
import type { Announcement } from '@/api/announcement/anTable'
import { addAnnouncementApi, adGetAnnouncesApi, deleteAnnouncementApi, editAnnouncementApi } from '@/api/announcement'
import Dialog from '@/components/dialog/Dialog.vue'
import useDialog from '@/hooks/usedialog'
import { useAdminStore } from '@/store/admin'
const useAdmin = useAdminStore()
//表单的ref属性
const formRef = ref<FormInstance>()
//弹框参数
const { dialog, onClose, onConfirm, onShow } = useDialog();
// 定义搜索表单接口
interface SearchForm {
    searchQuery: string
    isVisible: string
}

// 定义分页接口
interface Pagination {
    currentPage: number
    pageSize: number
    total: number
}

// 搜索表单数据
const searchForm = reactive<SearchForm>({
    searchQuery: '',
    isVisible: ''
})
//添加公告表单数据
const form = reactive<Announcement>({
    announcementId: '',
    anTitle: '',
    anContent: '',
    adminId: '',
    publishTime: '',
    isVisible: '',
    adminName: ''
})
//表单初始值
const initialForm = reactive<Announcement>({
    announcementId: '',
    anTitle: '',
    anContent: '',
    adminId: '',
    publishTime: '',
    isVisible: '',
    adminName: ''
})

// 表格加载状态
const loading = ref(false)

// 表格数据
const tableData = ref<Announcement[]>([])

// 分页数据
const pagination = reactive<Pagination>({
    currentPage: 1,
    pageSize: 10,
    total: 0
})
// 定义表单验证规则对象
const rule = reactive({
    anTitle: [
        { required: true, message: '请输入公告标题', trigger: 'blur' },
        { min: 3, max: 100, message: '公告标题长度在 3 到 100 个字符之间', trigger: 'blur' }
    ],
    anContent: [
        { required: true, message: '请输入公告内容', trigger: 'blur' },
        { min: 5, message: '公告内容至少需要 5 个字符', trigger: 'blur' }
    ]
})
//是否展示按钮
const handleSwitchChange = async (row: any) => { 
    const res = await editAnnouncementApi(row)
                if (res.code == 200) {
                    fetchData()
                    ElMessage.success(res.msg)
                    Object.assign(form, initialForm)
                    onClose()
                }
}

// 搜索方法
const handleSearch = () => {
    pagination.currentPage = 1
    fetchData()
}

// 重置搜索
const resetSearch = () => {
    searchForm.searchQuery = ''
    searchForm.isVisible = ''
    handleSearch()
}

// 处理页码变化
const handleCurrentChange = (page: number) => {
    pagination.currentPage = page
    fetchData()
}

// 处理每页条数变化
const handleSizeChange = (size: number) => {
    pagination.pageSize = size
    pagination.currentPage = 1
    fetchData()
}

// 获取表格数据方法
const fetchData = async () => {
    loading.value = true
    try {
        const res = await adGetAnnouncesApi(pagination.currentPage, pagination.pageSize, searchForm.searchQuery, searchForm.isVisible)
        if (res.code == 200) {
            ElMessage.success(res.msg)
            tableData.value = res.data.list
            pagination.total = res.data.total
            console.log(tableData.value)
        }
    } catch (error) {
        ElMessage.error('获取数据失败')
    } finally {
        loading.value = false
    }
}
const commit = () => {
    formRef.value?.validate(async (valid) => {
        if (valid) {
            if (dialog.title == "新增公告") {
                if (useAdmin.admin) {
                    form.adminId = useAdmin.admin.adminId
                    console.log(useAdmin.admin.adminId)
                    const res = await addAnnouncementApi(form)
                    if (res && res.code == 200) {
                        ElMessage.success(res.msg)
                        onClose()
                        fetchData()
                        Object.assign(form, initialForm)
                    }
                } else {
                    ElMessage.error("请进行管理员登录")
                }
            }
            if (dialog.title == "编辑公告") {
                
                const res = await editAnnouncementApi(form)
                if (res.code == 200) {
                    fetchData()
                    ElMessage.success(res.msg)
                    Object.assign(form, initialForm)
                    onClose()
                }

            }
        }
    })
}

// 新增公告
const handleAdd = () => {
    // 实现新增逻辑
    onShow()
    dialog.title = "新增公告"
}

// 编辑公告
const handleEdit = (row: Announcement) => {
    // 实现编辑逻辑
    onShow()
    Object.assign(form, row)
    dialog.title = "编辑公告"
}

// 查看公告
const handleView = (row: Announcement) => {
    // 实现查看逻辑
}

// 删除公告
const handleDelete = (row: Announcement) => {
    ElMessageBox.confirm(
        '确定要删除该公告吗？',
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(async () => {
        try {
            const res = await deleteAnnouncementApi(row.announcementId)
            if(res.code==200){
            ElMessage.success('删除成功')
            fetchData()
            }
        } catch (error) {
            ElMessage.error('删除失败')
        }
    }).catch(() => { })
}

// 组件挂载时获取数据
onMounted(() => {
    fetchData()
})
</script>

<style scoped>
.announcement-container {
    padding: 20px;
}

.search-card {
    margin-bottom: 20px;
}

.search-form {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    flex-wrap: wrap;
    gap: 10px;
}

.table-card {
    margin-bottom: 20px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}

:deep(.el-card__header) {
    padding: 15px 20px;
}

:deep(.el-card__body) {
    padding: 20px;
}
</style>